package com.study.algorithm.sort;

import java.util.Arrays;

public class HeapSort {
    public static void sort(int[] arr) {
        for (int i = arr.length - 1; i >= 0; i--) {
            heapify(arr, i, arr.length);
        }
        for (int i = arr.length - 1; i >= 0; i--) {
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;
            heapify(arr, 0, i);
        }
    }

    public static void heapify(int[] arr, int parent, int length) {
        int temp = arr[parent];
        int child = parent * 2 + 1;
        while (child < length) {
            if (child + 1 < length && arr[child + 1] > arr[child]) {
                child++;
            }
            if (temp >= arr[child]) {
                break;
            }
            arr[parent] = arr[child];
            parent = child;
            child = parent * 2 + 1;
        }
        arr[parent] = temp;
    }

    public static void main(String[] args) {
        int[] nums = {1, 5, 8, 7, 1, 2, 5, 4, 66, 5, 84, 5, 110, 4, 5, 4};
        sort(nums);
        System.out.println("nums = " + Arrays.toString(nums));
    }
}
